package com.wk.multi;

import java.lang.ref.WeakReference;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class GCTest {

    public static void main(String[] args) {
         ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 1,
                 TimeUnit.SECONDS, new LinkedBlockingDeque<>(10),new MyThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
         WeakReference<ThreadPoolExecutor> weakReference = new WeakReference<>(threadPoolExecutor);
         threadPoolExecutor.execute(() -> {
             System.out.println("worker: "+Thread.currentThread().getName()+"执行任务");
         });
        threadPoolExecutor = null;
        System.gc();
        if (weakReference.get() == null) {
            System.out.println("线程池被回收");
        }
        System.out.println(Thread.currentThread().getName()+"执行任务"+Thread.currentThread());

    }

    //当前线程 引用 线程池里的线程 引用 Executor
    static class MyThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Runnable runnable = ()->{
                System.out.println("线程真正执行");
                r.run();
                System.out.println("线程真正执行结束");
            };
            System.out.println("进入到wangke的线程工厂");
            return new Thread(runnable,"我自己的worker");
        }
    }

}

